<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字..."></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="menus" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="50">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="120">
			</el-table-column>
			<el-table-column prop="component" label="组件" width="150">
			</el-table-column>
			<el-table-column prop="url" label="url" width="130" sortable>
			</el-table-column>
			<el-table-column prop="icon" label="按钮类型" width="120" >
			</el-table-column>
      <el-table-column prop="index" label="索引" width="70" >
      </el-table-column>
      <el-table-column prop="parentId" label="父目录" width="120" >
        <template scope="bb">
          <span v-if="bb.row.parent" style="color: #20a0ff" >{{bb.row.parent.name}}</span>
          <span v-else style="color: #5e7382">无上级目录</span>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" >
        <template scope="aa">
          <span v-if="aa.row.state==true" style="color: #13ce66">启用</span>
          <span v-else style="color: red">禁用</span>
        </template>
      </el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage"
                     :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
		</el-col>

		<!--编辑和添加的对话框-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <!-- prop="name" 需要验证就加上这个属性，不需要验证就不加 -->
				<el-form-item label="名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="组件" prop="component">
          <el-input v-model="saveForm.component" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="url" prop="url">
          <el-input v-model="saveForm.url" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="按钮" prop="icon">
          <el-input v-model="saveForm.icon" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="索引" prop="index">
          <el-input v-model="saveForm.index" auto-complete="off"></el-input>
        </el-form-item>
        <!--
      下拉框的显示：
        v-for="item in managers" + 2个span
      回显机制：
        1.先根据v-model="saveForm.manager_id"中的manager_id从managers中找到回显哪一个对象
        2.但是对象中有很多属性，再通过:label="item.username" - 回显对象的username
      传值机制：
        1.当你选中某一个部门经理的时候，:value="item.id"  它会把选中对象的id
        2.赋值给v-model="saveForm.manager_id"中的manager_id
    -->
        <el-form-item label="父目录" prop="parentId">
          <el-cascader v-model="saveForm.parentId"
                       :options="menuTree"
                       :props="{
                checkStrictly: true,
                label: 'name',//级联框显示那个属性的值
                value: 'id'  //回显时需要，回传值时也需要
                 }"
                       clearable></el-cascader>
        </el-form-item>
				<el-form-item label="启用状态" >
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="true">启用</el-radio>
						<el-radio class="radio" :label="false">禁用</el-radio>
					</el-radio-group>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getMenuListPage, removeMenu, batchRemoveMenu, saveMenu, addMenu } from '../../api/api';

	export default {
		data() {
			return {
			  keyword: '',
			  //模型数据
        menus: [],
				totals: 0,
				currentPage: 1,
        pageSize:5,
				listLoading: false,//加载框
        //级联框模型数据
        menuTree: [],

				sels: [],//列表选中列

        //1.添加和修改的相关数据
        title: '',

				saveFormVisible: false,//控制对话框是否显示 - 默认不显示
				saveLoading: false,    //加载框
				saveFormRules: {
					name: [
						{ required: true, message: '请输入名称', trigger: 'blur' }
					],
				},


				//2.编辑界面数据
				saveForm: {
					id: null,
          name:'',
          component: '',
          url: '',
          icon: '',
          index: null,
          parentId: null,
          state: true,
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
          id: null,
          name:'',
          component: '',
          url: '',
          icon: '',
          index: null,
          parentId: null,
          state: true,
				}

			}
		},
		methods: {

      //1.批量删除按钮，选项改变的时候就会触发
    selsChange: function (sels) {
      this.sels = sels;
    },
    //2.批量删除
    batchRemove: function () {
      //获取数组中每一个对象的id，- 数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;//显示列表的加载框
        this.$http.patch("/menu/",ids).then(res =>{
          this.listLoading = false;
          if(res.data.success){
            this.$message("删除成功")
            this.getMenus();
          }else{
            this.$message.error("网络异常，请稍后重试【500】");
          }
        }).catch((res) =>{
          this.$message.error("网络异常，请稍后重试【服务器没开，404,400】")
        })
      }).catch(()=>{
      })
    },

      //3.删除
      handleDel: function (index, row) {
        this.$confirm("确认删除该记录吗？","提示",{
          type: 'warning'
        }).then(() =>{
          this.listLoading =true;
          this.$http.delete("/menu/"+row.id).then(res => {
                this.listLoading = false;
                if(res.data.success){
                  this.$message.success("删除成功");
                  this.getMenus();

                  //删除优化:计算总页数
                  var totalPage=Math.ceil(this.totals/this.pageSize);
                  //删除最后一页的最后一条数据，而且不能是第一页的时候，让当前页=当前页-1
                  if(
                      this.currentPage==totalPage &&(this.totals-1)%this.pageSize==0&& this.currentPage!=1
                  ){
                    this.currentPage =this.currentPage-1;
                  }
                }else{
                  this.$message.error("网络异常，请稍后重试【500】")
                }
            }).catch( res=>{
              this.message.error("网络异常，请稍后重试[服务器没开，404,400]")
          })
        }).catch(() => {
        })
      },
		  //4.高级查询
		  keywordQuery(){
        //防止高级查询时查询出为空的现象【当前是第5页，但是高级查询的结果没有5页】
        this.currentPage=1;
        this.getMenus();
      },
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getMenus();
			},
			//5.获取用户列表
			getMenus() {
			  //组装参数
				let para = {
					currentPage: this.currentPage,
          pageSize: this.pageSize,
          //高级查询的参数
          keyword: this.keyword
				};
				//显示加载框
				this.listLoading = true;
				//NProgress.start();

        this.$http.post("/menu",para).then(res =>{
          this.totals = res.data.totals;
          this.menus = res.data.data;
          this.listLoading = false
        }).catch(res =>{
          this.$message.error("网络繁忙，请稍后重试!!!")
            })
			},
			//6.显示编辑界面的对话框
			handleSave: function (index, row) {
        this.title = "编辑";
				this.saveFormVisible = true;
				this.saveForm = Object.assign({}, row);
        this.getMenuTree();
			},

			//7.显示新增界面的对话框
			handleAdd: function () {
        this.title = "添加";
				this.saveFormVisible = true;
				this.saveForm = {
          id: null,
          username: '',
          phone: '',
          email: '',
          password: '',
          age: null,
          state: true,
          parentId: null
				};
        this.getMenuTree();
			},
			//8.点击提交数据
			saveSubmit: function () {
        //将所有ref的表单【ref="saveForm"】,validate-验证
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
              //显示提交的加载框
							this.saveLoading = true;

							//解决上级菜单 下拉框选择出现的问题
							let para = Object.assign({}, this.saveForm);
							if(para.parentId==null || para.parentId.length==0){
							  para.parentId=null;
              }else if(para.parentId.length){
                para.parentId=para.parentId[para.parentId.length-1]
              }

              //发送请求
							this.$http.put("/menu",para).then((res) => {
                //关闭提交的加载框
								this.saveLoading = false;
                //关闭对话框
                this.saveFormVisible = false;

                if(res.data.success){
                  this.$message.success("操作成功");
                  this.getMenus();
                }else{
                  this.$message.error("系统异常，请稍后重试!【500】");
                }
							}).catch((res)=>{
                this.$message.error("系统异常，请稍后重试!【服务器没开,404,400,405】")
              })
						});
					}
				});
			},
      //10.获取菜单数
      getMenuTree(){
      this.$http.get("/menu/menuTree").then(res=>{
        this.menuTree = res.data;
      })
      }
		},
		mounted() {
			this.getMenus();
		}
	}

</script>

<style scoped>

</style>